package org.huiway.huipicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.huiway.huipicturebackend.exception.BusinessException;
import org.huiway.huipicturebackend.exception.ErrorCode;
import org.huiway.huipicturebackend.exception.ThrowUtils;
import org.huiway.huipicturebackend.manager.auth.StpKit;
import org.huiway.huipicturebackend.mapper.UserMapper;
import org.huiway.huipicturebackend.model.dto.picture.PictureUploadRequest;
import org.huiway.huipicturebackend.model.dto.user.ResetPasswordRequest;
import org.huiway.huipicturebackend.model.dto.user.UserQueryRequest;
import org.huiway.huipicturebackend.model.dto.user.UserRegisterRequest;
import org.huiway.huipicturebackend.model.entity.User;
import org.huiway.huipicturebackend.model.enums.UserRoleEnum;
import org.huiway.huipicturebackend.model.vo.picture.PictureVO;
import org.huiway.huipicturebackend.model.vo.user.LoginUserVO;
import org.huiway.huipicturebackend.model.vo.user.UserSelfVO;
import org.huiway.huipicturebackend.model.vo.user.UserVO;
import org.huiway.huipicturebackend.service.PictureService;
import org.huiway.huipicturebackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.huiway.huipicturebackend.constant.UserConstant.DEFAULT_AVATAR;
import static org.huiway.huipicturebackend.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author hh
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-06-25 10:30:38
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    @Lazy
    private PictureService pictureService;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @param pictureUploadRequest
     * @return
     */
    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest, MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String email = userRegisterRequest.getEmail();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        // 1. 校验
        if (StrUtil.hasBlank(email, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (email.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户邮箱（账号）过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // 2. 检查是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱重复");
        }
        //填充用户账号
        String userAccount = transUserAccount(email);
        queryWrapper.eq("userAccount", userAccount);
        count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号重复");
        }
        // 3. 加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 4. 插入数据
        User user = new User();
        user.setEmail(email);
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        if (multipartFile == null || multipartFile.isEmpty()) {
            user.setUserAvatar(DEFAULT_AVATAR);
        } else {
            PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, user);
            user.setUserAvatar(pictureVO.getUrl());
        }
//        // 上传头像
//        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, user);
//        user.setUserAvatar(pictureVO.getUrl());
        // 更新用户信息
        boolean result = this.updateById(user);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败，数据库错误");
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账号
     * @param email        用户邮箱
     * @param userPassword 用户密码
     * @param request
     * @return
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String email, String userPassword, HttpServletRequest request) {
        String userAccountOrEmail = userAccount;
        if (userAccount == null) {
            userAccountOrEmail = email;
        }
        // 1. 校验
        if (StrUtil.hasBlank(userAccountOrEmail, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccountOrEmail.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱/账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", userAccountOrEmail).or().eq("userAccount", userAccountOrEmail);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, email cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        //4. 记录用户登录态到 Sa-token，便于空间鉴权时使用，注意保证该用户信息与 SpringSession 中的信息过期时间一致
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        //先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 尝试获取当前登录用户（宽松模式，未登录返回null）
     */
    @Override
    public User tryGetLoginUser(HttpServletRequest request) {
        try {
            // 先判断是否已登录
            Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
            User currentUser = (User) userObj;
            if (currentUser == null || currentUser.getId() == null) {
                return null;
            }
            // 从数据库查询
            long userId = currentUser.getId();
            currentUser = this.getById(userId);
            return currentUser;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取已登录用户信息（脱敏）
     *
     * @param user
     * @return
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取脱敏‍后的单个用户信息
     *
     * @param user
     * @return
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户列表
     *
     * @param userList
     * @return
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    /**
     * 将查询请‍求转为 QueryWrapper 对象
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String email = userQueryRequest.getEmail();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(email), "email", email);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "hh";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 用户修改自身信息
     *
     * @param userSelfVO
     * @param pictureUploadRequest
     * @param multipartFile
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserSelf(UserSelfVO userSelfVO, PictureUploadRequest pictureUploadRequest, MultipartFile multipartFile, User user) {
        if (userSelfVO == null || user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String email = userSelfVO.getEmail();
        //旧密码
        String oldPassword = userSelfVO.getOldPassword();
        //新密码
        String newPassword = userSelfVO.getUserPassword();
        String checkPassword = userSelfVO.getCheckPassword();
        //如果用户没输入用户名，就和 user 中的用户名一致
        if (userSelfVO.getUserName() == null) {
            user.setUserName(user.getUserName());
        }
        user.setUserName(userSelfVO.getUserName());
        if (userSelfVO.getUserProfile() == null) {
            user.setUserProfile(user.getUserProfile());
        }
        user.setUserProfile(userSelfVO.getUserProfile());
        //校验
        if (email != null) {
            if (email.length() < 4) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户邮箱（账号）过短");
            }
            user.setEmail(userSelfVO.getEmail());
            //填充账号
            String userAccount = transUserAccount(email);
            user.setUserAccount(userAccount);
        }
        if (StrUtil.isNotBlank(email)) {
            //检查邮箱（账号）是否重复，除了自己那条对应的邮箱（账号）信息
            boolean exists = this.lambdaQuery()
                    .eq(User::getEmail, user.getEmail())
                    .ne(User::getId, user.getId())
                    .exists();
            if (exists) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱（账号）重复");
            }
        }
        if (oldPassword != null) {
            //先检验填写的旧密码是否和数据库中的一致
            String encryptOldPassword = getEncryptPassword(oldPassword);
            if (!encryptOldPassword.equals(user.getUserPassword())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧密码错误");
            }
            if (newPassword.length() < 8 || checkPassword.length() < 8) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
            }
            //加密
            String encryptNewPassword = getEncryptPassword(newPassword);
            String encryptCheckPassword = getEncryptPassword(checkPassword);
            if (!encryptNewPassword.equals(encryptCheckPassword)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
            }
            user.setUserPassword(encryptNewPassword);

        }
        if (multipartFile != null) {
            //图片上传
            PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, user);
            if (pictureVO != null) {
                user.setUserAvatar(pictureVO.getUrl());
            }
        }
        boolean result = this.updateById(user);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败，数据库错误");
        }
        return true;
    }

    /**
     * 重置密码
     *
     * @param resetPasswordRequest
     * @param loginUser
     * @return
     */
    @Override
    public boolean resetPassword(ResetPasswordRequest resetPasswordRequest, User loginUser) {
        if (resetPasswordRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        String email = resetPasswordRequest.getEmail();
        if (!email.equals(loginUser.getEmail())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户邮箱（账号）不一致");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        User user = this.getOne(queryWrapper);
        if (user == null || !user.getId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        String userPassword = resetPasswordRequest.getUserPassword();
        String checkPassword = resetPasswordRequest.getCheckPassword();
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        user.setUserPassword(getEncryptPassword(userPassword));
        boolean result = this.updateById(user);
        return result;
    }

    /**
     * 将用户邮箱转换为用户账号
     *
     * @param email
     * @return
     */
    private String transUserAccount(String email) {
        if (email == null || !email.contains("@")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        // 取 @ 前部分作为账号
        return email.substring(0, email.indexOf("@"));
    }
}




